package com.guoj.easyweb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guoj.easyweb.common.exception.CustomException;
import com.guoj.easyweb.common.utils.EncryptUtil;
import com.guoj.easyweb.common.utils.IDUtil;
import com.guoj.easyweb.common.utils.StatusCode;
import com.guoj.easyweb.entity.TbUser;
import com.guoj.easyweb.form.AppLoginForm;
import com.guoj.easyweb.form.LoginForm;
import com.guoj.easyweb.mapper.TbUserMapper;
import com.guoj.easyweb.service.ITbUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author guoj
 * @since 2019-06-20
 */
@Service
@Slf4j
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements ITbUserService {

	@Override
	public TbUser login(LoginForm loginForm) {

		// 表单密码转密文和数据库比对
		String passwordHex = DigestUtils.sha256Hex(loginForm.getPassword());

		TbUser user = baseMapper.selectOne(new QueryWrapper<TbUser>().eq("username", loginForm.getUsername()));

		if (user == null || !user.getPassword().equals(DigestUtils.sha256Hex(loginForm.getPassword() + user.getSalt()))) {
			log.error("用户名或密码错误");
			throw new CustomException("用户名或密码错误", StatusCode.LOGINERROR);
		}

		if (user.getFlag() == 0) {
			log.error("账号已被锁定,请联系管理员.");
			throw new CustomException("账号已被锁定,请联系管理员.", StatusCode.USERLOCKED);
		}

		return user;
	}

	@Override
	public TbUser appLogin(AppLoginForm loginForm) {

		// 表单密码转密文和数据库比对
		String passwordHex = DigestUtils.sha256Hex(loginForm.getPassword());

		TbUser user = baseMapper.selectOne(new QueryWrapper<TbUser>().eq("username", loginForm.getUsername()));

		if (user == null || !user.getPassword().equals(DigestUtils.sha256Hex(loginForm.getPassword() + user.getSalt()))) {
			log.error("用户名或密码错误");
			throw new CustomException("用户名或密码错误", StatusCode.LOGINERROR);
		}

		if (user.getFlag() == 0) {
			log.error("账号已被锁定,请联系管理员.");
			throw new CustomException("账号已被锁定,请联系管理员.", StatusCode.USERLOCKED);
		}

		return user;
	}


	@Override
	public int addUser(TbUser user) {
		TbUser tbUser = new TbUser();
		tbUser.setId(IDUtil.getId(1));
		tbUser.setUsername(user.getUsername());

		String[] encrypt = EncryptUtil.encrypt("");
		tbUser.setPassword(encrypt[0]);
		tbUser.setSalt(encrypt[1]);

		tbUser.setFlag(1);
		tbUser.setNickname(user.getNickname());
		tbUser.setSex(user.getSex());
		tbUser.setAddress(user.getAddress());
		tbUser.setHeaderImg("");
		tbUser.setCreateTime(LocalDateTime.now());

		int result = this.getBaseMapper().insert(tbUser);
		return result;
	}

}
